package company.permissionsystem.security;


import company.permissionsystem.security.auth.ExpiredSessionStrategy;
import company.permissionsystem.security.auth.LoginFailureHandler;
import company.permissionsystem.security.auth.LoginSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    LoginSuccessHandler loginSuccessHandler;

    @Resource
    LoginFailureHandler loginFailureHandler;

    @Resource
    UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .headers().frameOptions().sameOrigin();

        http.formLogin()
                .loginPage("/login")    //自定义登陆页面
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/login/form")
//                .defaultSuccessUrl("/index")    //登陆成功跳转页面
//                .failureUrl("/login")   //登陆失败跳转页面
                .successHandler(loginSuccessHandler)    //自定义登陆成功策略
                .failureHandler(loginFailureHandler)    //自定义失败策略

                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()  //放行资源
                .antMatchers("/", "/welcome", "/employee", "/department", "/position").authenticated()  //这里的路径只需要登陆即可访问，不需要权限
//                .anyRequest().access("@rabcService.hasPermission(request, authentication)")   //根据链接API来判断权限

                .and().sessionManagement()
                .maximumSessions(1)     //最大允许1个session登陆
                .maxSessionsPreventsLogin(false)     //允许再次登陆，但之前会下线
                .expiredSessionStrategy(new ExpiredSessionStrategy());
    }

    /**
     *  静态资源放行
     * */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/my/**", "/treetable-lay/**",
                "/xadmin/**", "/ztree/**", "/druid/**", "/swagger-resources/configuration/ui",
                "/swagger-resources/configuration/security",
                "/swagger-resources", "/v2/api-docs");
    }

    /**
     *  加载用户角色及其权限
     * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     *  密码加盐
     * */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     *  用于Controller层权限主键
     * */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


}
